import { defineStore } from 'pinia'
import { login, smsLogin } from '@/api/login'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),

  actions: {
    // 账号密码登录
    async loginByAccount(data) {
      const res = await login(data)
      this.setLoginState(res.data)
      return res
    },

    // 短信登录
    async loginBySms(data) {
      const res = await smsLogin(data)
      this.setLoginState(res.data)
      return res
    },

    // 设置登录状态
    setLoginState(data) {
      this.token = data.token
      this.userInfo = data.userInfo
      localStorage.setItem('token', data.token)
      localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
    },

    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
}) 